import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:二叉树右视图、根据二叉树创建字符串
 * Date: 2024-02-06
 * Time:21:59
 */
public class Solution {

    public List<Integer> rightSideView(TreeNode root) {
        if(root == null)
            return new ArrayList<>();
        //层序遍历，一层一个数组，每层取该层数组最后一个元素
        List<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            List<Integer> list1 = new ArrayList<>();
            int size = queue.size();
            while(size-- > 0) {
                TreeNode pop = queue.poll();
                if(pop.left != null) {
                    queue.offer(pop.left);
                }
                if(pop.right != null) {
                    queue.offer(pop.right);
                }
                list1.add(pop.val);
            }
            int last = list1.get(list1.size()-1);  //得到该层最右的节点的val
            list.add(last);
        }
        return list;
    }

///////////////////////////////////////////
StringBuilder ret = new StringBuilder();
    public String tree2str(TreeNode root) {
        if(root == null)
            return new String();
        ret.append(root.val);

        //对根节点进行分析
        //1.左右都空：不处理
        //2.左空右不空：补整个括号
        //3.左不空右空：不处理
        if(root.left != null) {
            ret.append('(');
            //处理左树
            tree2str(root.left);
            if(root.left != null)
                ret.append(')');  //处理完补右括号
        } else {
            if(root.right != null) {
                ret.append("()");
            }
        }

        if(root.right != null) {
            ret.append('(');
            tree2str(root.right);
            ret.append(')');
        }
        return ret.toString();
    }


}
